/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.web.xss.config;

import com.web.xss.filter.XssFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.Objects;

/**
 * Filter配置
 *
 * @author lirui
 */
@Configuration
public class FilterConfig {

    /**
     * 注册过滤器
     *
     * @param url 提供可不拦截接口
     *            实现配置不过滤部分接口，部分接口需要不做过滤
     * @return
     */
    @Bean
    public FilterRegistrationBean xssFilterRegistration(XssIgnoreFilterUrl url) {
        FilterRegistrationBean registration = getFilterRegistrationBean(url);
        return registration;
    }

    private FilterRegistrationBean getFilterRegistrationBean(XssIgnoreFilterUrl url) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        //指定发起请求时过滤
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter(Objects.isNull(url) ? null : url.getUrls()));
        //默认所有接口
        registration.addUrlPatterns("/*");
        registration.setName("xssFilter");
        //设置最后执行，防止有其他过滤器对值需要修改等操作，保证最后过滤字符即可
        registration.setOrder(Integer.MAX_VALUE);
        return registration;
    }
}
